<!DOCTYPE html>
<html>
<head>
  <title>Parenthesizator</title>
  <script src="parenthesize.js"></script>
  <script src="dom_manip.js"></script>
  <style>
  p.sol { font-family: monospace; }
  p.error { color: #c00; }
  </style>
</head>
<body>
  <h1>Parenthesizator</h1>
  <h2>Initial data</h2>
  <p>Input the expression without parenthesis (using +, -, * and / as operators) in the left hand side and the desired result in the right hand side:</p>
  <form>
  <input type="text" id="lhs">
  <strong>=</strong>
  <input type="text" id="rhs">
  </form>
  <h2>Solutions</h2>
  <div id="output">
  </div>
  <script>
// updates parenthesizations
function updateParenthesizations()
{
  // gets the expression and the result text strings
  var expr = $('lhs').value;
  var result = $('rhs').value;

  // cleans up output area
  cleanOutputArea();
  
  // if one or more of the inputs are empty, exits without error
  if (expr === '' || result === '') {
    return;
  }
  
  // checks these strings
  var error = false;
  if (!EXPRESSION_RE.test(expr)) {
    addError('Invalid expression syntax.');
    error = true;
  }
  if (!RESULT_RE.test(result)) {
    addError('Invalid result syntax.');
    error = true;
  }
  if (error) {
    return;
  }
  
  // gets the solutions
  try {
    var sols = parenthesize(expr, result);
  } catch(e) {
    alert('INTERNAL ERROR');
    return;
  }
  
  // if there are solutions, adds them to the output area
  if (sols.length > 0) {
    for (var i = 0; i < sols.length; i++) {
      addSolution(sols[i]);
    }
  } else {
    addError('There are no solutions.');
  }
}
  
// initialization function
function init()
{
  // adds the event handlers to update the solution *when the input is already updated*
  $('lhs').onkeyup = updateParenthesizations;
  $('rhs').onkeyup = updateParenthesizations;
}

init();
  </script>
</body>
</html>
